﻿/// <summary>
/// 数据库缓存
/// </summary>
public class DbCache : SqlSugar.ICacheService
{
    /// <summary>
    /// 添加缓存
    /// </summary>
    /// <typeparam name="V"></typeparam>
    /// <param name="key"></param>
    /// <param name="value"></param>
    public void Add<V>(string key, V value)
    {
        RedisHelper.Set(key, value);
    }

    /// <summary>
    /// 添加缓存
    /// </summary>
    /// <typeparam name="V"></typeparam>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <param name="cacheDurationInSeconds"></param>
    public void Add<V>(string key, V value, int cacheDurationInSeconds)
    {
        RedisHelper.Set(key, value, cacheDurationInSeconds);
    }

    /// <summary>
    /// 是否有这个缓存
    /// </summary>
    /// <typeparam name="V"></typeparam>
    /// <param name="key"></param>
    /// <returns></returns>
    public bool ContainsKey<V>(string key)
    {
        return RedisHelper.Exists(key);
    }

    /// <summary>
    /// 获取缓存
    /// </summary>
    /// <typeparam name="V"></typeparam>
    /// <param name="key"></param>
    /// <returns></returns>
    public V Get<V>(string key)
    {
        return RedisHelper.Get<V>(key);
    }

    /// <summary>
    /// 获取所有缓存的key
    /// </summary>
    /// <typeparam name="V"></typeparam>
    /// <returns></returns>
    public IEnumerable<string> GetAllKey<V>()
    {
        return RedisHelper.Keys("*");
    }

    /// <summary>
    /// 获取缓存 如果不存在则创建缓存
    /// </summary>
    /// <typeparam name="V"></typeparam>
    /// <param name="cacheKey"></param>
    /// <param name="create"></param>
    /// <param name="cacheDurationInSeconds"></param>
    /// <returns></returns>
    public V GetOrCreate<V>(string cacheKey, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
    {
        if (RedisHelper.Exists(cacheKey))
        {
            return RedisHelper.Get<V>(cacheKey);
        }

        V v = create();

        RedisHelper.Set(cacheKey, v, cacheDurationInSeconds);

        return v;
    }

    /// <summary>
    /// 删除缓存
    /// </summary>
    /// <typeparam name="V"></typeparam>
    /// <param name="key"></param>
    public void Remove<V>(string key)
    {
        RedisHelper.Del(key);
    }
}

